from django.shortcuts import render,redirect
from myApp.models import User,Comments,Movies
from django.http import HttpResponseRedirect
from django.contrib import messages
from utils.error import *
from utils.getPublicData import *
# Create your views here.

def home(request):
    try:
        username = request.session.get('username')
        userInfo = User.objects.get(username=username)
        getAllData()
    except:
        return render('login')
    return render(request,'home.html',{
        'userInfo':userInfo
    })

def login(request):
    if request.method == 'GET':
        return render(request, 'login.html',{})
    else:
        loginusername = request.POST.get('loginusername')
        loginpassword = request.POST.get('loginpassword')
        print(loginusername, loginpassword)
        try:
            user = User.objects.get(username=loginusername,password=loginpassword)
            request.session['username'] = loginusername
            return HttpResponseRedirect('/myApp/home/')
        except:
            message = '用户名或密码错误'
            messages.error(request, message)
            return HttpResponseRedirect('/myApp/login/')



def register(request):
    if request.method == 'GET':
        return render(request, 'register.html', {})
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        ckpassword = request.POST.get('ckpassword')
        try:
            User.objects.get(username=username)
            message = '用户已存在'
            messages.error(request, message)
            return HttpResponseRedirect('/myApp/register/')
        except:
            if not username or not password or not ckpassword:
                message = '请输入完整信息'
                messages.error(request, message)
                return HttpResponseRedirect('/myApp/register/')
            elif password != ckpassword:
                message = '两次密码不一致'
                messages.error(request, message)
                return HttpResponseRedirect('/myApp/register/')
            else:
                User.objects.create(username=username,password=password)
                messages.success(request,'注册成功')
                return HttpResponseRedirect('/myApp/login/')

def logout(request):
    request.session.clear()
    return redirect('/myApp/login/')